<!-- 组件代码如下 -->
<template>
  <div class="shopping-info animate_active"
       :style="shoppingShow ? 'right:0;' : ''">
    <div class="info">
      <p class="title">购物车<span @click="$parent.shoppingShow = !shoppingShow" style="float: right"><a>关闭</a></span></p>
      <ul class="shopping-ul">
        <li class="flex flex-a-center shopping-li"
            v-for="(item, key) in cartList"
            v-cloak
            :key="item.id">
          <!--<input type="checkbox"/>-->
          <div class="order-item">
            <div class="flex materials-info">
              <div class="info-left">
                <!--<div class="img">-->
                <el-image style="width: 100%;height: 200px" :src="item.fabricImg">
                  <div slot="error">
                    <i style="margin-top: 45%;" class="el-icon-picture-outline">暂无图片</i>
                  </div>
                </el-image>
                <!--</div>-->
                <!--                <span>供应商编号：{{ null }}</span>-->
                <span>面料编号：{{ item.fabricCode }}</span>
              </div>
              <ul class="info-right">
                <li>
                  <span class="span-lable">纱支</span>
                  <span>{{ item.fabricShazhi }}</span>
                </li>
                <li>
                  <span class="span-lable">成分</span>
                  <span>{{ item.fabricContent }}</span>
                </li>
                <li>
                  <span class="span-lable">克重</span>
                  <span>{{ item.fabricWeight }}</span>
                </li>
                <!--<li>
                    <span class="span-lable">花型</span>
                    <span>{{item.info4}}</span>
                </li>-->
                <li>
                  <span class="span-lable">颜色</span>
                  <span>{{ item.fabriceColor }}</span>
                </li>
                <li>
                  <span class="span-lable">幅宽</span>
                  <span>{{ item.fabricWidth }}</span>
                </li>
                <li>
                  <span class="span-lable">库存</span>
                  <span>{{ item.inventory }}</span>
                </li>
              </ul>
            </div>
            <div class="shopping-order-detail">
              <div class="flex flex-a-center detail-item">
                <span class="lable">购买米数</span>
                <div>
                  <!--<span @click="minus(item.id)">-</span>-->
                  <el-button @click="minus(item.id)">-</el-button>
                  <!--<input @blur="changeBuyNumberFunc(item.id,item.buyNumber)" type="number"
                                           v-model="item.buyNumber"/>-->
                  <el-input-number
                      :controls="false"
                      @blur="numberChange(item)"
                      v-model="item.buyNumber"></el-input-number>
                  <!--<span @click="add(item.id)">+</span>-->
                  <el-button @click="add(item.id)">+</el-button>
                </div>
              </div>
              <span v-show="item.buyNumber>=item.inventory" style="color:red">库存紧张，订单可能被驳回或备库</span>
              <div class="detail-item">
                <span class="lable">阶梯价</span>
                <span class="item-span-right">{{ item.fabricPrice }}元/米</span>
              </div>
              <div class="detail-item">
                <span class="lable">面料总额</span>
                <!--<span class="item-span-right red">{{item.num * item.price}}元</span>-->
                <span class="item-span-right red">{{ Number(item.totalAmount) }}元</span>
              </div>

              <div class="detail-item">
                <span class="lable">客户折扣</span>
                <span v-if="Number(item.discount)!=0" class="item-span-right red">{{
                    (Number(item.discount) * 100) + '%'
                  }}</span>
                <span v-if="Number(item.discount)==0" class="item-span-right red">100%</span>
              </div>

              <div class="detail-item">
                <span class="lable">备注</span>
                <span class="item-span-right" style="width: 200px"><el-input
                    type="textarea"
                    :rows="4"
                    @blur="updateBZ(item.id,item.remark)"
                    v-model="item.remark"/></span>
              </div>
              <div class="detail-item">
                <el-button style="background-color: #4c4c4c" type="primary"
                           @click="delCart(item.id)"><span
                    style="color:#f9d532;">删除</span></el-button>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <div class="flex btn-box">
      <div class="shopping flex-a-center">
        <!--<input type="checkbox" style="margin-top: 2px"/>-->
        <!--<span>全选</span>
        <p>
            已选
            <span class="red">2</span> 件
        </p>-->
        <p>
          合计（不含运费）
          <span class="red">{{ cartList.length > 0 ? cartList[0].zzzp : '' }}</span> 元
        </p>
      </div>
      <button type="submit" class="flex-1 Settlement" @click="checkData(),gotolink()">
        提交
      </button>
    </div>
  </div>
</template>
<script>
import {getAction} from "../api/manage";

export default {
  name: "shopping",
  created() {
    this.getCartList()
  },
  data() {
    return {
      orderSn: '',// 创建订单成功之后的ID
      autohor_token: localStorage.getItem("token"), //token
      allPrice: 0,
      url: {
        list: '/cart/getCartList', // 获取购物车列表
        decare: '/cart/decrByNum', //购物车数量减一
        incare: '/cart/incrByNum', // 购物车数量加一
        updateRemark: '/cart/updateRemark', // 更新备注
        changeBuyNumber: '/cart/changeBuyNumber', // 手动修改购买数量
        delCart: '/cart/deleteCart',// 删除购物车
        createFabricOrder: '/Order/createFabricOrder',// 创建一条未支付的订单
      },
      cartList: [], // 查询到的购物车列表
      cartids: [], // 购物车IDS
      shoppingList: [
        {
          id: 1,
          idNum1: '2561IOU',
          idNum2: 'LVII033147',
          info1: 'SUPER110`S',
          info2: '羊毛',
          info3: '260g',
          info4: '人字',
          info5: '米色',
          info6: '150cm',
          num: 2,
          price: '390'
        },
        {
          id: 2,
          idNum1: '2561IOU',
          idNum2: 'LVII033147',
          info1: 'SUPER110`S',
          info2: '羊毛',
          info3: '260g',
          info4: '人字',
          info5: '米色',
          info6: '150cm',
          num: 1,
          price: '390'
        }
      ],
    };
  },
  props: {
    shoppingShow: {
      type: Boolean
    }
  },
  mounted() {
  },
  methods: {

    changflag() {
      var f = true;
      f = true;
      f = true;
      f = false;
    },

    numberChange(item) {//面料米数的监听事件
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]+)?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      // var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (!reg.test(item.buyNumber)) {
        this.$message.warning("请输入正确的米数,比如1或1.1")
        item.buyNumber = '1';
        this.changeBuyNumberFunc(item.id, item.buyNumber)
        return
      } else {
        let inputnumber = item.buyNumber;//10.234  1.7777
        // alert(inputnumber+"==="+inputnumber.toString().split(".").length)
        item.buyNumber = Math.floor((inputnumber * 1 + 0.09) * 10) / 10;
        this.changeBuyNumberFunc(item.id, item.buyNumber)
        return;

        // if (inputnumber.toString().split(".").length == 0) {
        //   item.buyNumber = inputnumber;
        //   this.changeBuyNumberFunc(item.id, item.buyNumber)
        //   return;
        // } else {
        //   var number_zu = inputnumber.toString().split(".");
        //   // alert("拿了米=="+number_zu)
        //   var jisaun_number = inputnumber.toString().split(".").join("");
        //   // alert("数组=="+number_zu+"==涨肚="+number_zu.length+"=小数点后的=="+number_zu[1].length)
        //   if (number_zu[1].length >= 0 && number_zu[1].length < 2) {
        //     item.buyNumber = inputnumber;
        //     this.changeBuyNumberFunc(item.id, item.buyNumber)
        //     return;
        //   } else if (number_zu[1].length >= 2) {
        //     let num1 = jisaun_number / 100 + 0.1;
        //     let num2 = num1 * 10;
        //     let num3 = num2 / 10;
        //     var number_zu2 = num3.toString().split(".");
        //     let lostnum = number_zu2[0] + "." + number_zu2[1].substring(0, 1)
        //     // var str = num3.substring(0,num3.length-1);//截取第二个到第四个之间的字符 cd
        //     // alert(inputnumber+"==最后孩子=="+num1+"==="+num3+"==最后="+number_zu2+"=="+lostnum)
        //     item.buyNumber = lostnum;
        //     this.changeBuyNumberFunc(item.id, item.buyNumber)
        //     return;
        //   }
        // }
      }
    },
    /**
     * 修改备注
     */
    updateBZ(id, remark) {
      getAction(domain.publicUrl + this.url.updateRemark, {
        'id': id,
        'remark': remark
      }).then(res => {
        if (res.data.code == '0') {
          this.$message.success("修改成功")
        }
      })
    },

    checkData() { // 检查基本信息是否填写
      if (this.$store.state.stooreCode == '' || this.$store.state.stooreCode == null) {
        this.$message.error("请选择门店")
        return 1
      } /*else if (this.$store.state.packageType == '' || this.$store.state.packageType == null) {
                    this.$message.error("请选择包装方式")
                    return 1
                }*/ else if (this.$store.state.kuaidiID == '' || this.$store.state.kuaidiID == null) {
        this.$message.error("请选择快递方式")
        return 1
      } else if (this.$store.state.addressType == '' || this.$store.state.addressType == null) {
        this.$message.error("请选择地址类型")
        return 1
      } else if (this.$store.state.address == '' || this.$store.state.address == null) {
        this.$message.error("请填写地址")
        return 1
      } else {
        return 0
      }
      /*if (this.$store.state.threadSn == '' || this.$store.state.kuaidiID == null) {
          this.$message.error("******")
          return
      }*/
    },
    delCart(cartid) {// 逻辑删除购物车
      getAction(domain.publicUrl + this.url.delCart, {'id': cartid}).then(res => {
        if (res.data.code == '0') {
          this.$message.success("删除成功")
          this.cartList = res.data.data
          this.getCartList()
          if (this.cartList.length == 0) {
            // this.$parent.shoppingShow = false
            this.$parent.shoppingShow = !shoppingShow
          }
        }
      })
    },
    getCartList() { // 查询购物车列表
      this.cartids = []
      let ppp = 0
      getAction(domain.publicUrl + this.url.list, {'token': this.autohor_token}).then(res => {
        if (res.data.code == '0') {
          this.cartList = res.data.data
          if (this.cartList.length > 0) {
            for (var j = 0; j < this.cartList.length; j++) {
              this.cartids.push(this.cartList[j].id)
              ppp += Number(this.cartList[j].totalAmount)
            }
            this.allPrice = ppp
          } else {
            this.allPrice = 0
          }
        }
      })
    },
    // 购物车减一
    minus(cartID) {

      getAction(domain.publicUrl + this.url.decare, {
        'cartid': cartID,
        'token': this.autohor_token
      }).then(res => {
        if (res.data.code == '0') {
          this.getCartList()
          // this.$message.success(res.data.msg)
        } else if (res.data.code == '1') {
          // this.$message.error(res.data.msg)
        }
      })
      /*if (this.shoppingList[index].num != 1) {
          this.shoppingList[index].num--;
      }*/

    },

    /**
     * 购物车加一
     * @param cartID 购物车 ID
     */
    add(cartID) {
      getAction(domain.publicUrl + this.url.incare, {
        'cartid': cartID,
        'token': this.autohor_token
      }).then(res => {
        if (res.data.code == '0') {
          this.getCartList()
          // this.$message.success(res.data.msg)
        } else if (res.data.code == '1') {
          // this.$message.error(res.data.msg)
        }
      })
    },

    /**
     *手动修改购买米数
     * @param cartid 购物车ID
     * @param buynumber 购买米数
     */
    changeBuyNumberFunc(cartid, buynumber) {

      if (buynumber > 0) {
        getAction(domain.publicUrl + this.url.changeBuyNumber, {
          'cartid': cartid,
          'buyNum': buynumber,
          'token': this.autohor_token
        }).then(res => {
          if (res.data.code == '0') {
            this.getCartList()
            // this.$message.success("操作成功")
          } else if (res.data.code == '1') {
            this.getCartList()
            // this.$message.warning("库存不足")
          } else if (res.data.code == '2') {
            return
          } else if (res.data.code == '500' || res.data.code == '3') {
            this.getCartList()
            this.$message.warning("请输入正确的购买米数")
          }
        })
      } else {
        this.$message.warning("请输入正确的购买米数")
        this.getCartList()
      }
    },

    gotolink() { // 购物车提交订单（创建未支付订单）
      if (this.cartList == null || this.cartList.length == 0) {
        return
      }
      if (this.checkData() == 1) {
        return
      }
      getAction(domain.publicUrl + this.url.createFabricOrder, {
        'token': this.autohor_token,
        'packaging': this.$store.state.packageType,
        'courierId': this.$store.state.kuaidiID,
        'addressType': this.$store.state.addressType == '1' ? "门店地址" : "其他地址",
        'address': this.$store.state.address,
        'otherOrdersn': this.$store.state.threadSn,
        'cartId': this.cartids.toString(),
        'storeId': this.$store.state.storeid,
        'storeCode': this.$store.state.stooreCode,
        'name': this.$store.state.name,
        'phone': this.$store.state.phone
      }).then(res => {
        if (res.data.code == '0') {
          this.getCartList()
          this.$message.success(res.data.msg)
          this.shoppingShow = false
          this.orderID = res.data.data
          this.$router.push({path: '/my-order'})
          /*this.$parent.openBuy(this.allPrice, res.data.data)*/
        } else if (res.data.code == '1') {
          this.$message.error(res.data.msg)
        }
      })
    }
  },
};
</script>
<style>
[v-cloak] {
  display: none;
}
</style>
